﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;

using System.Text;
using System.Xml.Linq;

namespace pkrss.cmpLogin
{
    public partial class childLogin : ChildWindow
    {
        private string mEmail;
        private string mPassword;
        private string mService;

        private enum eOpType
        {
            eOp_none,
            eOp_loginRequest,   // 1.1
            eOp_loginResponse, // 1.2
            eOp_loginPost, // 1.3
            eOp_tokenRequest, // 2.1
            eOp_tokenResponse, // 2.2
            eOp_listRequest, // 3.1
            eOp_tokenPost, // 3.2
        };
        private eOpType mEventId;


        private Dictionary<string, string> mResponseMessages = null;

        private SynchronizationContext syncContext;
 

        public childLogin()
        {
            InitializeComponent();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        public void GetLogin(string service, string email, string password)
        {
            mEmail = email;
            mPassword = password;
            mService = service;

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("https://www.google.com/accounts/ClientLogin");
            
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            mEventId = eOpType.eOp_loginRequest;
            request.BeginGetRequestStream(new AsyncCallback(RequestReady), request); 
            
        }

        public void GetToken(string service, string email, string password)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("https://www.google.com/reader/api/0/token?client=scroll&ck=" + DateTime.Now.ToString("YYYYMMDD"));

            request.Method = "GET";
            request.Headers["Authorization"] = "GoogleLogin auth=" + mResponseMessages["Auth"];
            request.Headers["Cookie"] = "SID=" + mResponseMessages["SID"];

            mEventId = eOpType.eOp_tokenRequest;
            request.BeginGetResponse(new AsyncCallback(RequestReady), request);
        }

        public void GetList(string service, string email, string password)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("https://www.google.com/reader/api/0/tag/list?output=json");

            request.Method = "GET";
            request.Headers["Authorization"] = "GoogleLogin auth=" + mResponseMessages["Auth"];
            request.Headers["Cookie"] = "SID=" + mResponseMessages["SID"];
            request.Headers["accept-encoding"] = "gzip, deflate";

            mEventId = eOpType.eOp_listRequest;
            request.BeginGetResponse(new AsyncCallback(RequestReady), request);
        }

        private void RequestReady(IAsyncResult asyncResult)
        {
            System.IO.StreamWriter sw;
            WebResponse response;
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;

            switch (mEventId)
            {
                case eOpType.eOp_loginRequest: // 1.1
                    sw = new System.IO.StreamWriter(request.EndGetRequestStream(asyncResult));
                    sw.Write("accountType=HOSTED_OR_GOOGLE&Email=" + mEmail + "&Passwd=" + mPassword + "&service=" + mService + "&source=pkrss");

                    sw.Close();
                    sw.Dispose();

                    mEventId = eOpType.eOp_loginResponse;
                    request.BeginGetResponse(new AsyncCallback(RequestReady), request);
                    break;

                case eOpType.eOp_loginResponse: // 1.2
                    response = request.EndGetResponse(asyncResult) as WebResponse; // notify to main thread.

                    if (syncContext == null) syncContext = new SynchronizationContext();

                    mEventId = eOpType.eOp_loginPost;
                    syncContext.Post(ExtractResponse, response);
                    break;

                case eOpType.eOp_tokenRequest: // 2.1
                    response = request.EndGetResponse(asyncResult) as WebResponse; // notify to main thread.

                    if (syncContext == null) syncContext = new SynchronizationContext();
                    mEventId = eOpType.eOp_tokenResponse;
                    syncContext.Post(ExtractResponse, response);
                    break;

                case eOpType.eOp_listRequest: // 3.1
                    response = request.EndGetResponse(asyncResult) as WebResponse; // notify to main thread.

                    if (syncContext == null) syncContext = new SynchronizationContext();
                    mEventId = eOpType.eOp_tokenPost;
                    syncContext.Post(ExtractResponse, response);
                    break;
                
            }
        }

        private void ExtractResponse(object state)
        {
            System.Net.HttpWebResponse response = state as System.Net.HttpWebResponse;

            System.IO.StreamReader sr;

            switch (mEventId)
            {
                case eOpType.eOp_loginPost: // 1.3
                    try
                    {
                        sr = new System.IO.StreamReader(response.GetResponseStream());
                        int idx;
                        while (!sr.EndOfStream)
                        {
                            string line = sr.ReadLine();

                            idx = line.IndexOf('=');
                            if (idx == -1)
                                continue;

                            mResponseMessages[line.Substring(0, idx + 1)] = line.Substring(idx + 1);

                            // mResponseMessages
                            if (line.StartsWith("Auth"))
                            {
                                //       mResponseMessage = line.Replace("Auth=", "");
                                //       break;
                            }
                            // SID
                        }
                    }
                    finally
                    {
                        if (response != null)
                            response.Close();
                    }

                    mEventId = eOpType.eOp_none;
                    break;

                case eOpType.eOp_tokenResponse: // 2.2
                    try
                    {
                        sr = new System.IO.StreamReader(response.GetResponseStream());

                        mResponseMessages["Token"] = sr.ReadToEnd();
                    }
                    finally
                    {
                        if (response != null)
                            response.Close();
                    }

                    mEventId = eOpType.eOp_none;
                    break;

                case eOpType.eOp_tokenPost: // 3.2
                     try
                    {
                        sr = new System.IO.StreamReader(response.GetResponseStream());

                        // System.Json.JsonArray.Parse(sr.ReadToEnd())["tags"];
                        mResponseMessages["tags"] = sr.ReadToEnd(); // System.Json.JsonArray.Parse(sr.ReadToEnd());
                    }
                    finally
                    {
                        if (response != null)
                            response.Close();
                    }

                    mEventId = eOpType.eOp_none;
                    break;
            }
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            GetLogin("reader", "", "");
        }
    }
}

